package com.yyb.learn.jbasics.basic.designpattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Yamos
 * @description E_04DynamicProxy
 * @date 2021/3/1 0001 15:35
 */
public class E_04JDKProxy implements InvocationHandler {

    private Object target;

    public E_04JDKProxy() {
    }

    //定义获取代理对象方法
    public Object getProxyInstance(Object targetObject){
        //为目标对象target赋值
        this.target = targetObject;
        //JDK动态代理只能针对实现了接口的类进行代理，newProxyInstance 函数所需参数就可看出
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("pre method for every proxied method");
        method.invoke(target, args);
        System.out.println("after method for every proxied method");
        return null;
    }
}
